package com.itheima.interceptor;

import com.itheima.domain.vo.LoginUserInfo;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.ThreadUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("Authorization");
        if(token == null){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //解析token
        try {
            Claims claims = JwtUtil.parseJwt(token);
            Long userId = claims.get("userId", Long.class);
            String nickName = claims.get("nickName", String.class);
            String icon = claims.get("icon", String.class);
            ThreadUtil.set(new LoginUserInfo(userId,nickName,icon));
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadUtil.remove();
    }
}
